package com.foreverwin.jzymes.production.cutter.controller;

import com.foreverwin.jzymes.common.constant.Constants;
import com.foreverwin.jzymes.common.service.IFieldGroupAdviceService;
import com.foreverwin.jzymes.common.service.IItemGroupAdviceService;
import com.foreverwin.jzymes.common.service.ISiteAdviceService;
import com.foreverwin.jzymes.common.service.IToolAdiviceService;
import com.foreverwin.jzymes.common.util.BOHandleUtil;
import com.foreverwin.jzymes.common.util.CommonMethods;
import com.foreverwin.jzymes.framework.base.AjaxResult;
import com.foreverwin.jzymes.framework.base.BaseController;
import com.foreverwin.jzymes.framework.exception.BusinessException;
import com.foreverwin.jzymes.framework.util.I18nUtil;
import com.foreverwin.jzymes.framework.util.ObjectMapperUtil;
import com.foreverwin.jzymes.production.cutter.domain.ToolBreakLog;
import com.foreverwin.jzymes.production.cutter.mapper.ToolBreakAdiviceMapper;
import com.foreverwin.jzymes.production.cutter.service.IExportExcelService;
import com.foreverwin.jzymes.production.cutter.service.IToolBreakAdiviceService;
import com.foreverwin.jzymes.production.cutter.service.IToolBreakLogService;
import com.foreverwin.jzymes.production.tool.domain.ToolBill;
import com.foreverwin.jzymes.production.tool.service.IToolBillAdviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/production/cutter")
public class ToolBreakController extends BaseController {
    @Autowired
    IToolBreakAdiviceService toolBreakAdiviceService;
    @Autowired
    IToolBillAdviceService toolBillAdviceService;
    @Autowired
    IToolBreakLogService toolBreakLogService;
    @Autowired
    ISiteAdviceService siteAdviceService;
    @Autowired
    IItemGroupAdviceService itemGroupAdviceService;
    @Autowired
    IFieldGroupAdviceService fieldGroupAdviceService;
    @Autowired
    ToolBreakAdiviceMapper toolBreakAdiviceMapper;
    @Autowired
    IExportExcelService exportExcelService;

    /**新增数据*/
    @RequestMapping("/submit")
    public AjaxResult submit(@RequestBody ToolBreakLog toolBreakLog){
        try {

            toolBreakLog.setSite( CommonMethods.getSite() );
            toolBreakLog.setCreateType( "M" );
            toolBreakLog.setCreateUserBo(CommonMethods.getUserBo() );
            toolBreakLog.setHandle( BOHandleUtil.buildToolBreakHandle() );

            toolBreakAdiviceService.insertToolBreak( toolBreakLog );

            String breakType = toolBreakAdiviceMapper.selectfieldLabel( CommonMethods.getSite(),toolBreakLog.getBreakType() );
            toolBreakLog.setBreakType( breakType );
            return  AjaxResult.returnSuccess().put( "value" ,toolBreakLog );
        }catch (BusinessException e){
            return  AjaxResult.returnError( e.getMessage() );
        }
    }

    /**
     * 编辑换刀记录
     *
     * @param toolBreakLog
     * */
    @RequestMapping("/update")
    public AjaxResult update(@RequestBody ToolBreakLog toolBreakLog){
        try {
            toolBreakLog.setUpdateUserBo( CommonMethods.getUserBo() );
            toolBreakLog.setUpdatedDateTime( new Date() );
            toolBreakLog.setSite( CommonMethods.getSite() );
            toolBreakAdiviceService.updateToolBreak( toolBreakLog );

            String breakType = toolBreakAdiviceMapper.selectfieldLabel( CommonMethods.getSite(),toolBreakLog.getBreakType() );
            toolBreakLog.setBreakType( breakType );

            return  AjaxResult.returnSuccess().put( "value" ,toolBreakLog );
        }catch (BusinessException e){
            return  AjaxResult.returnError( e.getMessage() );
        }
    }

    /**
     * 检索换刀信息
     *
     * @param jsonMap
     * @return
     */
    @RequestMapping("/ToolBreakByreport")
    public AjaxResult ToolBreakByreport(@RequestParam Map<String,Object> jsonMap){
        try {
            jsonMap.put( "site" , CommonMethods.getSite() );

            List<ToolBreakLog>  logList = toolBreakAdiviceService.selectToolBreak( jsonMap );
            return  AjaxResult.returnSuccess().put( "value" , logList );
        }catch (BusinessException e){
            return  AjaxResult.returnError( e.getMessage() );
        }
    }

    /**
     * 删除换刀信息
     *
     * @param list
     * @return
     */
    @RequestMapping("/delete")
    public AjaxResult deleteToolBreak( @RequestBody List< String > list ){

        try{
            toolBreakAdiviceService.deleteToolBreak( list );
            return AjaxResult.returnSuccess();
        }catch ( BusinessException e ) {
            return AjaxResult.returnError( e.getMessage() );
        }
    }

    /**
     * 导出excel
     * @param paramJson
     * @param response
     * @param request
     */
    @RequestMapping("/doexport")
    public void doexport(String  paramJson , HttpServletResponse response, HttpServletRequest request ){

        try{
            List<String> list = ObjectMapperUtil.readValue( paramJson, ArrayList.class );
            List< ToolBreakLog> toolBreakLogs = new ArrayList<>();
            String[] rowName = new String[]{"序号","更换时间","机种","班次","设备编号","夹位","刀号","刀具型号","标准寿命","实际寿命","数量","换刀类型","品牌","批次号","生技员","备注","创建日期"};
            String title = "换刀信息";
            String excel = "ToolBreak.xls";
            List<Object[]> dataList = new ArrayList<Object[]>();
            Object[] objs = null;
            for( int i = 0; i < list.size(); i++ ){
                ToolBreakLog toolBreakLog = new ToolBreakLog();
                toolBreakLog = toolBreakLogService.selectToolBreakLogById( list.get(i) );
                SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                objs = new Object[rowName.length];
                objs[0] = i;
                objs[1] = sd.format( toolBreakLog.getChgTime() );
                objs[2] = toolBreakLog.getMachineType();
                objs[3] = toolBreakLog.getShift();
                objs[4] = toolBreakLog.getResrce();
                objs[5] = toolBreakLog.getCncType();
                objs[6] = toolBreakLog.getToolLoc();
                objs[7] = toolBreakLog.getToolType();
                objs[8] = toolBreakLog.getMaxUsage();
                objs[9] = toolBreakLog.getActualUsage();
                objs[10] = toolBreakLog.getQty();
                objs[11] = toolBreakLog.getBreakType();
                objs[12] = toolBreakLog.getBrand();
                objs[13] = toolBreakLog.getLotNo();
                objs[14] = toolBreakLog.getTechnicion();
                objs[15] = toolBreakLog.getRemark();
                objs[16] = sd.format( toolBreakLog.getCreatedDateTime() );

                dataList.add(objs);
            }

           File file = exportExcelService.Export( dataList , title ,rowName ,excel );

           fileDownload( file,true,response,request );

        }catch (Exception e ) {
            throw  BusinessException.build(e.getMessage());
        }
    }

    @RequestMapping("/maxUsage")
    public AjaxResult maxUsage( @RequestParam String machineType,@RequestParam String cncType,@RequestParam String toolLoc ){

        try{
            String site = CommonMethods.getSite();
            /**检查站点*/
            siteAdviceService.existSite( site );
            /**检查机种*/
            itemGroupAdviceService.existItemGroup( site, machineType );
            /**检查夹位*/
            fieldGroupAdviceService.existFieldGroup( site , Constants.FIELD_GROUP_CncType , cncType );
            /**当前版本刀具清单*/
            ToolBill toolBill = toolBillAdviceService.selectToolBillByMachineTypeCncType( site , machineType ,cncType );
            if ( toolBill == null ){
                throw BusinessException.build("production.tool.ToolBillByMachineTypeCncType",new String[]{ machineType,cncType } );
            }
            String bo = toolBill.getHandle();
            /**检查刀号*/
            fieldGroupAdviceService.existFieldGroup( site , Constants.FIELD_GROUP_ToolLoc , toolLoc );
            Map<String,Object> maxUsage = toolBreakAdiviceMapper.selectmaxUsage( bo , toolLoc );
            /**刀号在刀具清单中信息不存在*/
            if ( maxUsage == null ){
                throw BusinessException.build("production.cutter.toolLocMaxUsageNotExist" , new String[]{ toolLoc });
            }
            Map<String,Object> retMap = new HashMap<>();
            retMap.put("maxUsage", maxUsage.get("MAX_USAGE"));
            retMap.put("toolType",maxUsage.get("TOOL_TYPE"));
            return AjaxResult.returnSuccess().put( "value" , retMap );
        }catch ( BusinessException e ) {
            return AjaxResult.returnError( e.getMessage() );
        }
    }

}
